import { Button, Form, Input, InputRef, message } from "antd";
import { ModalProps } from 'antd';
import CommonModal from "./CommonModal";
import { SvgIcon } from "@/components/icon";
import { useEffect, useState } from 'react';

import { setItem } from '@/utils/storage';
import { StorageEnum } from '@/types/enum';
import React from "react";
import { hashStr } from "@/utils/common";

type Props = {
  showCancelBtn?: boolean;
  showOkBtn?: boolean;
} & ModalProps;


const LoginModal = ({ open, onOk, onCancel, title }: Props) => {
  const [messageApi, contextHolder] = message.useMessage();
  const inputRef = React.createRef<InputRef>();

  const handleFinish = async ({username, password}) => {
    try {
      const response = await fetch('/openapi/v1/user/login', {
        body: JSON.stringify({
          username: username,
          password: hashStr(password),
        }),
        headers: {
          'Content-Type': 'application/json',
        },
        method: 'POST',
      });

      let data = await response.json()

      if (data?.code == 1 && data?.message) {
        messageApi.error(data.message)
      }

      if (data?.code == 0 && onOk) {
        const mergeUser = { username: username, id: username };
        setItem(StorageEnum.User, mergeUser)
        onOk();
      }
    } catch (error) {
      console.error('登录请求失败:', error);
    }
  };

  useEffect(()=>{
    inputRef.current?.focus()
  }, [inputRef.current])

  return (
    <CommonModal showCancelBtn={false} showOkBtn={false} open={open} width={'450px'}>
      {contextHolder}
      <div className='text-lg'>
        <SvgIcon className="mt-[-50px] mb-[-50px]" icon="ic-logo" size={'280px'} style={{ color: 'green' }}></SvgIcon>
      </div>
      <Form
        name="login_form"
        size="large"
        className="w-8/12"
        onFinish={handleFinish}
      >
        <Form.Item
          name="username"
          rules={[{ required: true, message: '请输入用户名' }]}
        >
          <Input ref={inputRef} id="username"  className="h-10" placeholder='请输入用户名' />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input.Password id="password" className="h-10" placeholder='请输入密码' />
        </Form.Item>
        <Form.Item>
          <Button id="login"
            type="primary"
            htmlType="submit"
            className="w-full mt-5"
            style={{ height: '40px', borderRadius: '20px' }}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </CommonModal>
  );
};

export default LoginModal;
